package cn.ssm.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.ssm.pojo.OrderDetail;
import cn.ssm.pojo.OrderSeat;
import cn.ssm.service.OrderDetailService;
import cn.ssm.service.SeatService;
import cn.ssm.service.UserService;
import cn.ssm.util.DateUtil;
import cn.ssm.util.OrderThread;

/**
 * 订单详情控制类
 * 
 * @author 黄少涛
 *
 */
@Controller
@RequestMapping("/order")
public class OrderDetailController {
	@Autowired
	private OrderDetailService orderDetailService;
	@Autowired
	private SeatService seatService;
	@Autowired
	private UserService userservice;

	@Resource(name = "taskExecutor")
	private TaskExecutor taskExecutor;

	int orderId = 0;

	// 查询全部订单
	@RequestMapping("/getOrderList")
	@ResponseBody
	public Object getOrderList(String movieName, Integer userId, Integer nowPage, Integer size) {
		// 入参
		Map<String, Object> paramas = new HashMap<String, Object>();
		/*
		 * int intnowPage = nowPage; int intsize=size; int start =
		 * (intnowPage-1)*intsize; Integer integerStart = start;
		 */
		paramas.put("start", (nowPage - 1) * size);
		paramas.put("size", size);
		paramas.put("movieName", movieName);
		paramas.put("userId", userId);

		// 返回值
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);

		try {
			List<OrderDetail> orderDetails = orderDetailService.getOrderList(paramas);

			map.put("result", orderDetails);
			map.put("message", "查询订单列表成功！");
			map.put("success", true);
		} catch (Exception e) {
			map.put("message", "查询订单列表出现异常！");
			e.printStackTrace();
		}

		// String jsonString = JSON.toJSONString(map);

		return map;
	}

	// 查询订单总数量
	@RequestMapping("/getOrderCount")
	@ResponseBody
	public Object getOrderCount(Integer userId, String date) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);

		Map<String, Object> params = new HashMap<String, Object>(); // 传参
		params.put("userId", userId);
		params.put("date", date);

		try {
			int conut = orderDetailService.getOrderCount(params);
			map.put("result", conut);
			map.put("message", "查询订单成功！");
			map.put("success", true);

		} catch (Exception e) {
			map.put("massage", "查询订单列表出现异常！");
			e.printStackTrace();
		}

		return map;
	}

	// 根据排片id与订单座位查找座位是否已订，如果未订则进入线程同步方法增加订单
	@RequestMapping("/getOrderSeatBySchedule")
	@ResponseBody
	@Transactional // 事务处理
	public Object getOrderSeatBySchedule(String param, HttpSession session) { // 返回map字符串

		Map<String, Object> maps = new HashMap<String, Object>(); // 返回的map
		Map<String, Object> map = JSON.parseObject(param, Map.class); // 用json把传参转为map
		JSONObject jso = JSON.parseObject(param); // 获取json对象
		String string = (String) jso.get("scheduleId");
		Integer scheduleId = Integer.valueOf(string);
		JSONArray jsonArray = jso.getJSONArray("seats"); // 获取json数组

		String userPhone = (String) jso.get("userPhone"); // 获取手机号码存入session用户发送短信
		session.setAttribute("userPhone", userPhone);

		try {
			// 线程同步代码块
			synchronized (this) {
				int conut = orderDetailService.getOrderSeatBySchedule(map); // 查询所选座位是否已被购买
				if (conut > 0) {
					maps.put("success", false);
					maps.put("message", "所选的座位中有已订状态，请重新选座！！！");
					return maps;
				} else {
					// Integer scheduleId =(Integer) map.get("scheduleId");
					int num = orderDetailService.addOrder(map); // 增加订单
					if (num == 0) {
						new RuntimeException(); // 如果等于0表示失败 新建一个异常触发回滚跳出
					}
					OrderDetail orderDetail = orderDetailService.getOrderMaxIdMaxBuyDate(); // 查询最新订单的id与购买时间
					maps.put("result", orderDetail.getId()); // 储存新订单Id
					orderId = orderDetail.getId(); // 赋值订单ID
					for (Object seat : jsonArray) {
						String[] split = ((String) seat).split("_"); // 拆分获得实际位置
						Integer row = Integer.valueOf(split[0]);
						Integer line = Integer.valueOf(split[1]);
						int seatId = seatService.getSeatIdByRowAndLine(row, line, scheduleId); // 通过实际座位位置与排片id找到座位Id
						String str = "" + row + "_" + line + "";
						int a = seatService.addOrderSeat(new Integer(orderDetail.getId()), new Integer(seatId), str); // 插入已订座位模本到关系表
						if (a == 0) {
							new RuntimeException(); // 如果等于0表示失败 新建一个异常触发回滚跳出
						}

					}
					maps.put("message", "订票成功");
					maps.put("success", true);

				}

				taskExecutor.execute(new Runnable() { // 开启线程

					@Override
					public void run() {
						int threadOrderId = orderId;
						try {
							Thread.sleep(120000);

						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						Map<String, Object> map = new HashMap<String, Object>();
						Map<String, Object> param = new HashMap<String, Object>();
						Map<String, Object> params2 = new HashMap<String, Object>();
						map.put("orderId", threadOrderId);
						param.put("orderId", threadOrderId);
						param.put("activeId", 3);
						int num = orderDetailService.getOrderIsActiveId(map); // 根据订单ID查询订单状态Id
						if (num == 1) { // 等于1为未付款

							orderDetailService.updateOrder(param); // 更新订单状态3为取消
							List<OrderSeat> orderSeats = seatService.getOrderSeat(map); // 获取订单的座位

							for (OrderSeat orderSeat : orderSeats) { // 循环修改座位的模板
								int setId = orderSeat.getSeatId();
								String orderSeatStr = orderSeat.getOrderSeat();
								String newOrderSeat = orderSeatStr.replace("_", "-");
								params2.put("orderId", threadOrderId);
								params2.put("seatId", setId);
								params2.put("orderSeat", newOrderSeat);
								seatService.updateOrderSeat(params2);
								params2.clear();

							}
						}

					}
				});

			}
			

		} catch (Exception e) {
			maps.put("message", "出现异常，订票失败，请联系管理员");
			e.printStackTrace();
		}

		return maps;

	}

	// 通过订单Id查询订单详情
	@RequestMapping("/getOrderByOrderId")
	@ResponseBody
	public Object getOrderByOrderId(Integer orderId) {
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("success", false);
		params.put("orderId", orderId);

		try {
			List<OrderDetail> orderList = orderDetailService.getOrderList(params);
			OrderDetail orderDetail = orderList.get(0);
			map.put("result", orderDetail);
			map.put("success", true);
			map.put("message", "查询订单成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("message", "查询订单失败");
		}
		return map;

	}

	// 通过兑换码查询订单详情
	@RequestMapping("/getOrderByCode")
	@ResponseBody
	public Object getOrderByCode(String orderCode) {
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("success", false);
		params.put("orderCode", orderCode);

		try {
			List<OrderDetail> orderList = orderDetailService.getOrderList(params);
			OrderDetail orderDetail = orderList.get(0);
			map.put("result", orderDetail);
			map.put("success", true);
			map.put("message", "查询兑换码成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("message", "没有此兑换码");
		}
		return map;

	}

	// 通过订单Id修改订单状态编号
	@RequestMapping("/updateOrder")
	@ResponseBody
	public Object updateOrder(Integer orderId, Integer activeId) {
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		params.put("orderId", orderId); // 订单编号
		params.put("activeId", activeId); // 状态编号

		try {
			int num = orderDetailService.updateOrder(params);
			if (num > 0) {
				map.put("success", true);
				map.put("message", "修改订单状态成功");
			} else {
				map.put("message", "修改订单状态失败");
			}

		} catch (Exception e) {
			map.put("message", "修改订单出现异常，请联系管理员!");
			e.printStackTrace();
		}

		return map;
	}

	// 通过订单Id删除订单信息
	@RequestMapping("/deleteOrder")
	@ResponseBody
	public Object deleteOrder(Integer orderId) {
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("success", false);
		params.put("orderId", orderId); // 订单编号

		try {
			int num = orderDetailService.deleteOrder(params);
			if (num > 0) {
				map.put("result", num);
				map.put("success", true);
				map.put("message", "删除订单状态成功");
			} else {
				map.put("message", "删除订单状态失败");
			}
		} catch (Exception e) {
			map.put("message", "删除订单出现异常，请联系管理员!");
			e.printStackTrace();
		}
		return map;
	}

	// 通过订单Id 查询订单状态Id
	@RequestMapping("/getOrderIsActiveId")
	@ResponseBody
	public Object getOrderIsActiveId(Integer orderId) {

		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("success", false);
		params.put("orderId", orderId); // 订单编号

		try {
			int num = orderDetailService.getOrderIsActiveId(params);
			if (num > 0) {
				map.put("result", num);
				map.put("success", true);
				map.put("message", "删除订单状态成功");
			} else {
				map.put("message", "删除订单状态失败");
			}
		} catch (Exception e) {
			map.put("message", "删除订单出现异常，请联系管理员!");
			e.printStackTrace();
		}
		return map;
	}

	// 获取当天的总收入
	@RequestMapping("/getTodaySum")
	@ResponseBody
	public Object getTodaySum(String date) {

		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("success", false);
		params.put("date", date);

		try {
			double num = orderDetailService.getTodaySum(params);

			map.put("result", num);
			map.put("success", true);
			map.put("message", "查询总价成功");

		} catch (Exception e) {
			map.put("message", "查询总价出现异常，请联系管理员!");
			e.printStackTrace();
		}
		return map;

	}

	// 获取每月用户与订单的增加量
	@RequestMapping("/getMonthUserAndOrderCount")
	@ResponseBody
	public Object getMonthUserAndOrderCount() {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);

		try {
			List<String> orderCounts = orderDetailService.getOrderMonthData();
			List<String> userCounts = userservice.getUserMonthDate();
			map.put("orderResult", orderCounts);
			map.put("userResult", userCounts);
			map.put("success", true);
			map.put("message", "查询成功");

		} catch (Exception e) {
			map.put("message", "查询出现异常，请联系管理员!");
			e.printStackTrace();
		}
		return map;

	}

	// 根据UserName（电话号码）查对应的订单 朱海松
	@RequestMapping("/getListByUserName.htm")
	@ResponseBody
	public Object getListByUserName(Integer nowPage, Integer size) {
		// 入参
		Map<String, Object> paramas = new HashMap<String, Object>();

		paramas.put("start", (nowPage - 1) * size);
		paramas.put("size", size);

		// 返回值
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);

		try {
			List<OrderDetail> orderDetails = orderDetailService.getListByUserName(paramas);
			map.put("result", orderDetails);
			map.put("message", "查询订单列表成功！");
			map.put("success", true);
		} catch (Exception e) {
			map.put("message", "查询订单列表出现异常！");
			e.printStackTrace();
		}
		return map;
	}

	// 根据UserName（电话号码）查对应的订单总数 朱海松
	@RequestMapping("/getCountByUserName.htm")
	@ResponseBody
	public Object getCountByUserName() {
		// 接收的参数
		Map<String, Object> paramas = new HashMap<String, Object>();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);

		try {
			int count = orderDetailService.getCountByUserName(paramas);
			map.put("result", count);
			map.put("message", "查询订单成功！");
			map.put("success", true);

		} catch (Exception e) {
			map.put("message", "查询订单列表出现异常！");
			e.printStackTrace();
		}

		return map;
	}

}
